package cn.schoolwow.ams.test.module.quickdao.aware;

import cn.schoolwow.ams.domain.block.common.operation.OpenDialogBlockOperation;
import cn.schoolwow.ams.domain.block.list.clazz.ClazzListBlockConfigAware;
import cn.schoolwow.ams.domain.block.list.clazz.ClazzListBlockOption;
import cn.schoolwow.ams.domain.block.list.clazz.crud.ClazzListBlockListListener;
import cn.schoolwow.ams.domain.block.list.common.ListBlockPagingResponse;
import cn.schoolwow.ams.test.module.quickdao.domain.DatabaseTable;
import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.util.domain.beanCopy.BeanCopy;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DatabaseTableAware extends ClazzListBlockConfigAware {
    @Autowired
    private DAO starterDAO;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public ClazzListBlockOption getAMSBlockConfig() {
        ClazzListBlockOption clazzListBlockOption = new ClazzListBlockOption(
                "test", "数据库表", DatabaseTable.class
        );
        clazzListBlockOption.listBlockShowOption.requestFieldNames = new String[]{"tableName"};
        clazzListBlockOption.clazzListBlockAPIListener.listListener = new ClazzListBlockListListener() {
            @Override
            public ListBlockPagingResponse list(JSONObject conditionMap) throws Exception {
                List<Entity> entityList = new ArrayList<>();
                if(conditionMap.containsKey("tableName")){
                    entityList.add(starterDAO.getDatabaseEntity(conditionMap.getString("tableName")));
                }else{
                    entityList.addAll(starterDAO.getDatabaseEntityList());
                }
                List<DatabaseTable> databaseTableList = BeanCopy.cloneObjectList(entityList, DatabaseTable.class);
                return new ListBlockPagingResponse(databaseTableList);
            }
        };
        {
            OpenDialogBlockOperation openDialogBlockOperation = new OpenDialogBlockOperation("字段列表", applicationContext.getBean(DatabasePropertyAware.class));
            openDialogBlockOperation.routerFieldNameMap.put("tableName", "tableName");
            clazzListBlockOption.blockOperationList.add(openDialogBlockOperation);
        }
        return clazzListBlockOption;
    }
}
